import requests
from requests import utils
import re
from lxml import etree
def get_return(code,message):
    return {"code":code,"message":message}
class TrainingChina:
    headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) ''Chrome/51.0.2704.63 Safari/537.36'}
    cookies = None
    index_url = "http://www.training-china.com/index.html"
    login_url = "http://www.training-china.com/loginvalidate.html"
    def __init__(self):
        response = requests.get(url=self.index_url,headers=self.headers)
        self.cookies = response.cookies
    def login_with_plain(self,username,password):
        data = {"from":"http://www.training-china.com/index.html","rememberMe":"on"}
        data["login_username"] = username
        data["login_password"] = password
        response = requests.post(data=data,url=self.login_url,cookies=self.cookies,headers=self.headers)
        if re.search("帐号或密码不正确",response.text):
            return get_return(403,"用户名或密码不正确")
        else:
            return get_return(200,"登录成功")
    def finish_class(self,class_url):
        class_url = str(class_url).replace(".html","/finish.html")
        data = dict()
        data["playTime"] = 2100
        response = requests.post(data=data,url=class_url,cookies=self.cookies,headers=self.headers)
        if re.search("恭喜您完成了课时",response.text):
            return get_return(200,"刷课完成")
        else:
            return get_return(403,"请先登录")
    def get_courses(self):
        home_url = "http://www.training-china.com/person/home"
        response = requests.get(url=home_url,cookies=self.cookies,headers=self.headers)
        # fp = open("index.html","w+",encoding="utf-8")
        # fp.write(response.text)
        selector=etree.HTML(response.text)
        courses = selector.xpath(r"/html/body/section[2]/div/div/div[2]/div[2]/div/div/div/div[2]/div[1]/a")
        courses_list=list()
        for o in courses:
            courses_list.append({"href":"http://www.training-china.com/"+o.attrib["href"],"name":o.text})
        return courses_list
    def get_classes(self,course_url,course_name):
        response = requests.get(url=course_url,cookies=self.cookies,headers=self.headers)
        selector=etree.HTML(response.text)
        courses = selector.xpath(r'/html/body/section[2]/div/div/div[1]/div[2]/ul[2]/div/div/div[2]/div/ul/li/ul/li/a')
        class_list=list()
        for o in courses:
            class_list.append({"href":"http://www.training-china.com/"+o.attrib["href"],"name":"("+course_name+")"+o.attrib["title"]})
        print(class_list)
        return class_list
        
